package com.mentalhealthplatform.global.ratelimited;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Service
public class RateLimiterService {
    // 最大请求次数
    private static final int MAX_REQUEST_COUNT = 15000000;
    // 窗口期（毫秒）
    private static final long WINDOW_INTERVAL = 6000L;
    // 冷却时间（毫秒）
    private static final long COOLDOWN_INTERVAL = 10000L;


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    // 检查限流逻辑
    public boolean isRateLimited(String clientIp) {
        String requestCountKey = "rateLimiter:" + clientIp + ":count";
        String cooldownKey = "rateLimiter:" + clientIp + ":cooldown";

        Boolean isCooldown = redisTemplate.hasKey(cooldownKey);
        if (Boolean.TRUE.equals(isCooldown)) {
            return true;
        }

        Integer requestCount = (Integer) redisTemplate.opsForValue().get(requestCountKey);
        if (requestCount == null) {
            requestCount = 0;
        }

        if (requestCount >= MAX_REQUEST_COUNT) {
            redisTemplate.opsForValue().set(cooldownKey, "1", COOLDOWN_INTERVAL, TimeUnit.MILLISECONDS);
            redisTemplate.delete(requestCountKey);
            return true;
        }

        redisTemplate.opsForValue().increment(requestCountKey);
        redisTemplate.expire(requestCountKey, WINDOW_INTERVAL, TimeUnit.MILLISECONDS);
        return false;
    }

    // 获取冷却期剩余时间（秒）
    public long getCooldownRemaining(String clientIp) {
        String cooldownKey = "rateLimiter:" + clientIp + ":cooldown";
        Long remainingTime = redisTemplate.getExpire(cooldownKey, TimeUnit.SECONDS);
        return remainingTime != null ? remainingTime : 0;
    }
}
